<template>
  <div class="orders">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>我的订单</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="container">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入订单号或商品名称"
          clearable
          @keyup.enter="handleSearch"
          style="width: 300px; margin-right: 10px;"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleResetSearch">重置</el-button>
      </div>

      <!-- 订单状态筛选 -->
      <div class="order-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部订单" name="all" />
          <el-tab-pane label="待支付" :name="OrderStatus.PENDING_PAYMENT.toString()" />
          <el-tab-pane label="待发货" :name="OrderStatus.PENDING_SHIPMENT.toString()" />
          <el-tab-pane label="待收货" :name="OrderStatus.PENDING_RECEIPT.toString()" />
          <el-tab-pane label="已完成" :name="OrderStatus.COMPLETED.toString()" />
          <el-tab-pane label="已取消" :name="OrderStatus.CANCELLED.toString()" />
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div class="order-list" v-loading="loading">
        <div v-if="orders.length > 0">
          <div v-for="order in orders" :key="order.id" class="order-item">
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-no">订单号：{{ order.orderNo }}</span>
                <span class="order-time">{{ formatDate(order.createdAt) }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.orderStatus)">
                  {{ getStatusText(order.orderStatus) }}
                </el-tag>
              </div>
            </div>

            <!-- 订单商品 -->
            <div class="order-goods">
              <div v-if="order.items && order.items.length > 0">
                <div v-for="item in order.items" :key="item.id" class="goods-item">
                  <div class="goods-image">
                    <img :src="item.productImage || '/placeholder.svg'" :alt="item.productName" />
                  </div>
                  <div class="goods-info">
                    <h4>{{ item.productName }}</h4>
                    <p v-if="item.skuSpecifications" class="goods-spec">
                      {{ formatSpecifications(item.skuSpecifications) }}
                    </p>
                    <div class="goods-price">
                      <span class="price">¥{{ item.price }}</span>
                      <span class="quantity">x{{ item.quantity }}</span>
                    </div>
                  </div>
                  <div class="goods-total">
                    ¥{{ item.totalAmount }}
                  </div>
                </div>
              </div>
              <div v-else class="no-goods">
                <p>暂无商品信息</p>
              </div>
            </div>

            <!-- 订单金额 -->
            <div class="order-amount">
              <div class="amount-info">
                <span>共{{ getTotalQuantity(order.items) }}件商品</span>
                <span class="total">实付款：¥{{ order.totalAmount }}</span>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <el-button size="small" @click="viewOrder(order.id)">
                查看详情
              </el-button>

              <el-button
                v-if="order.orderStatus === OrderStatus.PENDING_PAYMENT"
                type="primary"
                size="small"
                @click="payOrder(order.id)"
              >
                立即支付
              </el-button>

              <el-button
                v-if="order.orderStatus === OrderStatus.PENDING_PAYMENT"
                size="small"
                @click="cancelOrder(order.id)"
              >
                取消订单
              </el-button>

              <el-button
                v-if="order.orderStatus === OrderStatus.PENDING_RECEIPT"
                type="success"
                size="small"
                @click="confirmOrder(order.id)"
              >
                确认收货
              </el-button>


            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!loading" class="empty-orders">
          <el-empty :description="getEmptyDescription()">
            <el-button type="primary" @click="$router.push('/')">
              去购物
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalPages > 1">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalPages * pageSize"
          layout="prev, pager, next, jumper"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useOrderStore } from '@/stores/order'
import { OrderStatus, type Order, type OrderItem } from '@/api/order'

const router = useRouter()
const orderStore = useOrderStore()

// 响应式数据
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

// 计算属性
const orders = computed(() => orderStore.orders)
const totalPages = computed(() => orderStore.totalPages)

// 方法
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatSpecifications = (specs: any) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ')
}

const getStatusType = (status: OrderStatus) => {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: 'warning',
    [OrderStatus.PENDING_SHIPMENT]: 'success',
    [OrderStatus.PENDING_RECEIPT]: 'info',
    [OrderStatus.COMPLETED]: 'success',
    [OrderStatus.CANCELLED]: 'danger',
    [OrderStatus.REFUNDING]: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: OrderStatus) => {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: '待支付',
    [OrderStatus.PENDING_SHIPMENT]: '待发货',
    [OrderStatus.PENDING_RECEIPT]: '待收货',
    [OrderStatus.COMPLETED]: '已完成',
    [OrderStatus.CANCELLED]: '已取消',
    [OrderStatus.REFUNDING]: '退款中'
  }
  return statusMap[status] || '未知状态'
}

const getTotalQuantity = (items: OrderItem[] | undefined) => {
  if (!items || !Array.isArray(items)) return 0
  return items.reduce((total, item) => total + item.quantity, 0)
}

const getEmptyDescription = () => {
  const descriptions: Record<string, string> = {
    'all': '暂无订单',
    [OrderStatus.PENDING_PAYMENT.toString()]: '暂无待支付订单',
    [OrderStatus.PENDING_SHIPMENT.toString()]: '暂无待发货订单',
    [OrderStatus.PENDING_RECEIPT.toString()]: '暂无待收货订单',
    [OrderStatus.COMPLETED.toString()]: '暂无已完成订单',
    [OrderStatus.CANCELLED.toString()]: '暂无已取消订单'
  }
  return descriptions[activeTab.value] || '暂无订单'
}

const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  currentPage.value = 1
  fetchOrders()
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchOrders()
}

const fetchOrders = async () => {
  try {
    loading.value = true
    
    const orderStatus = activeTab.value === 'all' ? undefined : parseInt(activeTab.value) as OrderStatus
    
    await orderStore.getOrders({
      page: currentPage.value,
      limit: pageSize.value,
      orderStatus,
      orderNo: searchKeyword.value || undefined
    })
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

const handleResetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  fetchOrders()
}

const viewOrder = (orderId: number) => {
  router.push(`/order/detail/${orderId}`)
}

const payOrder = (orderId: number) => {
  router.push(`/order/pay/${orderId}`)
}

const cancelOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确认取消订单？取消后无法恢复', '提示', {
      confirmButtonText: '确认取消',
      cancelButtonText: '继续支付',
      type: 'warning'
    })

    await orderStore.cancelOrder(orderId)
    ElMessage.success('订单已取消')

    // 刷新订单列表
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

const confirmOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确认收货？确认后订单将完成', '提示', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'info'
    })

    await orderStore.confirmOrder(orderId)
    ElMessage.success('确认收货成功')

    // 刷新订单列表
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 生命周期
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders {
  min-height: 100vh;
  background: #f5f5f5;
}

.breadcrumb {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-bar {
  background: white;
  margin: 20px 0;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.order-tabs {
  background: white;
  margin: 20px 0;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-list {
  margin-bottom: 20px;
}

.order-item {
  background: white;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.order-no {
  font-weight: 600;
  color: #333;
}

.order-time {
  color: #666;
  font-size: 14px;
}

/* 订单商品 */
.order-goods {
  padding: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  flex: 1;
}

.goods-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.goods-spec {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.goods-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.goods-price .price {
  font-size: 16px;
  font-weight: 600;
  color: #ff6900;
}

.goods-price .quantity {
  font-size: 14px;
  color: #666;
}

.goods-total {
  font-size: 18px;
  font-weight: 600;
  color: #ff6900;
}

/* 订单金额 */
.order-amount {
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e0e0e0;
}

.amount-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-info .total {
  font-size: 18px;
  font-weight: 600;
  color: #ff6900;
}

/* 订单操作 */
.order-actions {
  padding: 15px 20px;
  text-align: right;
  border-top: 1px solid #e0e0e0;
}

.order-actions .el-button {
  margin-left: 10px;
}

/* 空状态 */
.empty-orders {
  background: white;
  padding: 60px 20px;
  margin: 20px 0;
  border-radius: 8px;
  text-align: center;
}

.no-goods {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .goods-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .goods-image {
    align-self: center;
  }

  .goods-total {
    align-self: flex-end;
  }

  .amount-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-actions {
    text-align: center;
  }

  .order-actions .el-button {
    margin: 5px;
  }
}
</style>
